package com.eastmoney.emis.edda.infrastructure.report.service;

import com.eastmoney.emis.edda.domain.valueobject.TimeFormatter;
import com.eastmoney.emis.edda.infrastructure.report.MockMultipartFile;
import com.eastmoney.emis.edda.infrastructure.report.ReportType;
import com.eastmoney.emis.edda.infrastructure.report.po.EmhkHsbcReportFilePo;
import com.eastmoney.emis.edda.infrastructure.report.repository.ReportRepository;
import com.eastmoney.emis.logger.LoggerFactory;
import com.eastmoney.emis.utils.common.po.BaseResponse;
import org.apache.http.entity.ContentType;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Optional;

@Service
public class ReportFileService {

    private static final Logger log = LoggerFactory.getLogger(ReportFileService.class);
    @Autowired
    private BasicFileService basicFileService;

    @Autowired
    private ReportRepository repository;
    private static final String MODULE = "hsbcedda";
    private static final String FILE_SUFFIX = ".zip";


    public void upload(byte[] data, String date, ReportType reportType) {
        if(date == null) {
            date = LocalDate.now().minusDays(1).format(TimeFormatter.YYYY_MM_DD);
        }
        String extInfo = reportType.formatFileName(date);
        String fileNameWithSuffix = extInfo + FILE_SUFFIX;
        MultipartFile multipartFile = new MockMultipartFile(extInfo, fileNameWithSuffix, ContentType.APPLICATION_OCTET_STREAM.toString(), data);
        BaseResponse<String> response = basicFileService.uploadFile(multipartFile, MODULE, extInfo);
        if(response.getStatus() == 0) {
            log.info("upload file to minio success, file-path: {}", response.getData());
        } else {
            log.warn("upload file to minio error, msg: {}", response.getMessage());
            return;
        }
        repository.save(LocalDateTime.now(), extInfo, response.getData(), reportType);
    }

    public boolean exists(String reportDate, ReportType reportType) {
        return repository.exists(reportDate, reportType);
    }
    public String findDownloadPath(String reportDate, ReportType reportType) {
        EmhkHsbcReportFilePo emhkHsbcReportFilePo = repository.findByDateAndType(reportDate, reportType);
        return Optional.ofNullable(emhkHsbcReportFilePo).map(r -> r.MINIOFILENAME).orElse(null);
    }

}
